package com.example.Blog.filter;

import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;

import java.io.IOException;

@Component
@WebFilter(filterName = "LoginFilter", urlPatterns = "/*")
public class LoginFilter implements Filter {
    public static final AntPathMatcher PATH_MATCHER = new AntPathMatcher();

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse,
                         FilterChain filterChain)
            throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        String requestURI = request.getRequestURI();
        String[] urls = {
                "/login",
                "/logOut",
                "/css/**",
                "/js/**",
                "/photo/**"
        };

        // 检查是否需要登录才能访问的路径
        boolean requiresLogin = check(requestURI, urls);
        if (requiresLogin) {
            // 如果需要登录，检查用户是否已登录
            if (request.getSession().getAttribute("loginUser") != null) {
                // 用户已登录，允许访问
                filterChain.doFilter(request, response);
            } else {
                // 用户未登录，重定向到登录页面
                response.sendRedirect("/login");
            }
            return;
        }

        // 其他情况，允许访问
        filterChain.doFilter(request, response);
    }

    public boolean check(String requestURI, String[] urls) {
        for (String url : urls) {
            boolean match = PATH_MATCHER.match(url, requestURI);
            if (match)
                return true;
        }
        return false;
    }
}
